package com.adwin.addcoin.ui.login

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.BuildConfig
import com.adwin.addcoin.R
import com.adwin.addcoin.base.BaseActivity
import com.adwin.addcoin.databinding.LoginActivityBinding
import com.adwin.addcoin.ui.main.MainActivity
import com.adwin.addcoin.utils.dataStore
import com.adwin.addcoin.utils.getRePost
import com.adwin.addcoin.utils.installRepost
import com.adwin.addcoin.utils.saveToken
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.Profile
import com.facebook.ProfileTracker
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.identity.Identity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.FileNotFoundException
import java.io.FileReader
import java.io.IOException


class LoginActivity : BaseActivity<LoginActivityBinding, LoginViewModel>(
    LoginViewModel::class.java
) {
    var profileTracker: ProfileTracker? = null


    private val googleLoginLauncher =
        registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                try {
                    val account = Identity.getSignInClient(this)
                        .getSignInCredentialFromIntent(result.data)
                    AddCoinApplication.myLog("google login get account info id:${account.id}")
                    AddCoinApplication.myLog("google login get account info googleIdToken:${account.googleIdToken}")
                    AddCoinApplication.myLog("google login get account info password:${account.password}")
                    AddCoinApplication.myLog("google login get account info givenName:${account.givenName}")
                    AddCoinApplication.myLog("google login get account info familyName:${account.familyName}")
                    AddCoinApplication.myLog("google login get account info displayName:${account.displayName}")
                    AddCoinApplication.myLog("google login get account info profilePictureUri:${account.profilePictureUri}")
                    viewModel?.login(this, "google", account.googleIdToken)
                } catch (e: Exception) {
                    e.printStackTrace()
                    AddCoinApplication.myLog("google login get account info error :${e.message}")
                }
            }

        }

    private val metaCallbackManager by lazy { CallbackManager.Factory.create() }

//    private val facebookLoginLauncher =
//        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
//            if (result.resultCode == RESULT_OK){
//                metaCallbackManager.onActivityResult()
//            }
//        }


    override fun inflater(): LoginActivityBinding {
        return DataBindingUtil.setContentView(this, R.layout.login_activity)
    }

    override fun initActivity() {
        if (AddCoinApplication.isCloak){
            binding.btnLoginVisitor.visibility = View.VISIBLE
        }else{
            binding.btnLoginVisitor.visibility = View.GONE
        }
        viewModel?.checkKeyStoreHash()
        binding.vm = viewModel
        binding.lifecycleOwner = this
        LoginManager.getInstance()
            .registerCallback(metaCallbackManager, object : FacebookCallback<LoginResult> {
                override fun onCancel() {
                    AddCoinApplication.myLog("Meta login canceled")
                }

                override fun onError(error: FacebookException) {
                    AddCoinApplication.myLog("Meta login failed error:${error.message}")
                }


                override fun onSuccess(result: LoginResult) {
                    AddCoinApplication.myLog("Meta login success")
                    AddCoinApplication.myLog("Meta login account info userId:${result.accessToken.userId}")
                    AddCoinApplication.myLog("Meta login account info token:${result.accessToken.token}")
                    AddCoinApplication.myLog("Meta login account info token:${result.accessToken}")
                    AddCoinApplication.myLog("Meta login account info applicationId:${result.accessToken.applicationId}")
                    AddCoinApplication.myLog("Meta login account info authenticationToken:${result.authenticationToken}")
                    AddCoinApplication.myLog("Meta login account info authenticationToken:${result.authenticationToken?.token}")

                    viewModel?.login(this@LoginActivity, "facebook", result.accessToken.token)
                }

            })
        profileTracker = object : ProfileTracker() {
            override fun onCurrentProfileChanged(oldProfile: Profile?, currentProfile: Profile?) {
                currentProfile?.run {
                    AddCoinApplication.myLog("Meta  onCurrentProfileChanged id:$id")
                    AddCoinApplication.myLog("Meta  onCurrentProfileChanged firstName:$firstName")
                    AddCoinApplication.myLog("Meta  onCurrentProfileChanged middleName:$middleName")
                    AddCoinApplication.myLog("Meta  onCurrentProfileChanged lastName:$lastName")
                    AddCoinApplication.myLog("Meta  onCurrentProfileChanged name:$name")
                    AddCoinApplication.myLog("Meta  onCurrentProfileChanged linkUri:$linkUri")
                }
            }
        }
        //开始跟踪用户信息变化
        profileTracker?.startTracking()

        binding.btnLoginGoogle.setOnClickListener {
//            lifecycleScope.launch(Dispatchers.IO){
//                installRepost("start_google_login")
//            }
            MainScope().launch (Dispatchers.IO){
                installRepost("clickGoogle")
            }
            viewModel?.googleLogin { pendingIntent ->
                googleLoginLauncher.launch(IntentSenderRequest.Builder(pendingIntent).build())
            }
        }
        binding.btnLoginFacebook.setOnClickListener {
//            viewModel?.facebookLogin(this, metaCallbackManager)
//            LoginManager.getInstance().logIn(this, listOf("public_profile"))
            MainScope().launch (Dispatchers.IO){
                installRepost("clickFacebook")
            }
            LoginManager.getInstance().logInWithReadPermissions(this, listOf("email", "user_photos", "public_profile"))
        }
        binding.btnNoticeClose.setOnClickListener {
            binding.layoutNotice.visibility = View.INVISIBLE
        }
        binding.btnLoginVisitor.setOnClickListener {
            viewModel?.guestLogin(this)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        try {
            metaCallbackManager.onActivityResult(requestCode, resultCode, data)
        } catch (e: java.lang.Exception) {
            AddCoinApplication.myLog(e.localizedMessage)
        }

        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        LoginManager.getInstance().unregisterCallback(metaCallbackManager)
        profileTracker?.stopTracking()
        super.onDestroy()
    }
}